from flask import Blueprint, render_template, request, jsonify
from llm.doubao import call_doubao_api
from flask import request

# Create the blueprint here instead of importing it
bp = Blueprint('bunnywrite', __name__)


@bp.route('/write')
def bunnywrite():
    """
    Route for the bunnywrite feature - a writing practice interface
    Detects mobile devices and serves appropriate template
    """
    # Check if user agent is mobile
    user_agent = request.headers.get('User-Agent')
    is_mobile = any(device in user_agent.lower() for device in ['iphone', 'android', 'mobile'])

    # Return mobile or desktop template accordingly
    template = 'write_mobile.html' if is_mobile else 'write.html'
    return render_template(template)


@bp.route('/api/get-completion', methods=['POST'])
def get_completion():
    """
    API endpoint to get text completion from Doubao
    """
    text = request.json.get('text', '')
    prompt = f"Continue this English text with no more than 30 characters. Only provide the new part, do not repeat any existing text: {text}"
    completion = call_doubao_api(prompt)
    return jsonify({'completion': completion})
